//
//  IMAdStrategyModels.m
//  DualMediationSDK
//
//  广告策略相关模型实现
//  Created by YeJary on 2025/7/15.
//

#import "IMAdStrategyModels.h"

@implementation IMAdStrategyRequest

+ (instancetype)requestWithAppId:(NSString *)appId uuid:(NSString *)uuid {
    IMAdStrategyRequest *request = [[IMAdStrategyRequest alloc] init];
    request.app_id = appId;
    request.uuid = uuid;
    return request;
}

- (NSDictionary *)toDictionary {
    return @{
        @"app_id": self.app_id ?: @"",
        @"uuid": self.uuid ?: @""
    };
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMAdStrategyRequest: app_id=%@, uuid=%@>", self.app_id, self.uuid];
}

@end

@implementation IMSDKStartupConfig

+ (instancetype)configFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    
    IMSDKStartupConfig *config = [[IMSDKStartupConfig alloc] init];
    
    // 处理布尔类型的配置参数
    id logValue = dictionary[@"sdk_config_log"];
    if ([logValue isKindOfClass:[NSString class]]) {
        config.sdk_config_log = @([logValue boolValue]);
    } else if ([logValue isKindOfClass:[NSNumber class]]) {
        config.sdk_config_log = logValue;
    }
    
    id newUserDayValue = dictionary[@"sdk_config_new_user_day"];
    if ([newUserDayValue isKindOfClass:[NSString class]]) {
        config.sdk_config_new_user_day = @([newUserDayValue integerValue]);
    } else if ([newUserDayValue isKindOfClass:[NSNumber class]]) {
        config.sdk_config_new_user_day = newUserDayValue;
    }
    
    id userSwitchValue = dictionary[@"sdk_config_user_switch"];
    if ([userSwitchValue isKindOfClass:[NSString class]]) {
        config.sdk_config_user_switch = @([userSwitchValue boolValue]);
    } else if ([userSwitchValue isKindOfClass:[NSNumber class]]) {
        config.sdk_config_user_switch = userSwitchValue;
    }
    
    id usPrivacyValue = dictionary[@"sdk_config_us_privacy"];
    if ([usPrivacyValue isKindOfClass:[NSString class]]) {
        config.sdk_config_us_privacy = @([usPrivacyValue boolValue]);
    } else if ([usPrivacyValue isKindOfClass:[NSNumber class]]) {
        config.sdk_config_us_privacy = usPrivacyValue;
    }
    
    id adTrackValue = dictionary[@"sdk_config_ad_track"];
    if ([adTrackValue isKindOfClass:[NSString class]]) {
        config.sdk_config_ad_track = @([adTrackValue boolValue]);
    } else if ([adTrackValue isKindOfClass:[NSNumber class]]) {
        config.sdk_config_ad_track = adTrackValue;
    }
    
    id adLoadTrackValue = dictionary[@"sdk_config_ad_load_track"];
    if ([adLoadTrackValue isKindOfClass:[NSString class]]) {
        config.sdk_config_ad_load_track = @([adLoadTrackValue boolValue]);
    } else if ([adLoadTrackValue isKindOfClass:[NSNumber class]]) {
        config.sdk_config_ad_load_track = adLoadTrackValue;
    }
    
    // 处理字符串类型的配置参数
    config.sdk_config_adjust_event = dictionary[@"sdk_config_adjust_event"];
    
    // 处理 sdk_config_sdk_type 参数
    config.sdk_config_sdk_type = dictionary[@"sdk_config_sdk_type"];
    
    config.sdk_config_fb_ctl = dictionary[@"sdk_config_fb_ctl"];
    config.sdk_config_fb_level_event = dictionary[@"sdk_config_fb_level_event"];
    
    return config;
}

- (NSDictionary *)toDictionary {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    if (self.sdk_config_log) {
        dict[@"sdk_config_log"] = self.sdk_config_log;
    }
    if (self.sdk_config_new_user_day) {
        dict[@"sdk_config_new_user_day"] = self.sdk_config_new_user_day;
    }
    if (self.sdk_config_user_switch) {
        dict[@"sdk_config_user_switch"] = self.sdk_config_user_switch;
    }
    if (self.sdk_config_us_privacy) {
        dict[@"sdk_config_us_privacy"] = self.sdk_config_us_privacy;
    }
    if (self.sdk_config_adjust_event) {
        dict[@"sdk_config_adjust_event"] = self.sdk_config_adjust_event;
    }
    if (self.sdk_config_sdk_type) {
        dict[@"sdk_config_sdk_type"] = self.sdk_config_sdk_type;
    }
    if (self.sdk_config_ad_track) {
        dict[@"sdk_config_ad_track"] = self.sdk_config_ad_track;
    }
    if (self.sdk_config_ad_load_track) {
        dict[@"sdk_config_ad_load_track"] = self.sdk_config_ad_load_track;
    }
    if (self.sdk_config_fb_ctl) {
        dict[@"sdk_config_fb_ctl"] = self.sdk_config_fb_ctl;
    }
    if (self.sdk_config_fb_level_event) {
        dict[@"sdk_config_fb_level_event"] = self.sdk_config_fb_level_event;
    }
    
    return [dict copy];
}

+ (instancetype)defaultConfig {
    IMSDKStartupConfig *config = [[IMSDKStartupConfig alloc] init];
    config.sdk_config_log = @(YES);
    config.sdk_config_new_user_day = @(0);
    config.sdk_config_user_switch = @(NO);
    config.sdk_config_us_privacy = @(NO);
    config.sdk_config_adjust_event = nil;
    config.sdk_config_sdk_type = @"IS&MAX";
    config.sdk_config_ad_track = @(YES);
    config.sdk_config_ad_load_track = @(YES);
    config.sdk_config_fb_ctl = @"0;2;100";
    config.sdk_config_fb_level_event = nil;
    return config;
}

+ (instancetype)configWithDictionary:(NSDictionary *)dictionary {
    return [self configFromDictionary:dictionary];
}

- (BOOL)isValid {
    // 基本验证：检查必要的配置项
    if (self.sdk_config_sdk_type && self.sdk_config_sdk_type.length > 0) {
        NSArray *validTypes = @[@"IS&MAX", @"IS", @"MAX"];
        if (![validTypes containsObject:self.sdk_config_sdk_type]) {
            return NO;
        }
    }
    return YES;
}

- (NSString *)configDescription {
    return [self description];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMSDKStartupConfig: log=%@, newUserDay=%@, userSwitch=%@, usPrivacy=%@, adjustEvent=%@, sdkType=%@, adTrack=%@, adLoadTrack=%@, fbCtl=%@, fbLevelEvent=%@>",
            self.sdk_config_log, self.sdk_config_new_user_day, self.sdk_config_user_switch, self.sdk_config_us_privacy,
            self.sdk_config_adjust_event, self.sdk_config_sdk_type, self.sdk_config_ad_track, self.sdk_config_ad_load_track,
            self.sdk_config_fb_ctl, self.sdk_config_fb_level_event];
}

@end

@implementation IMAdCondition

+ (instancetype)conditionFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    
    IMAdCondition *condition = [[IMAdCondition alloc] init];
    
    // 处理cur_level，可能是字符串或数字
    id curLevelValue = dictionary[@"cur_level"];
    if ([curLevelValue isKindOfClass:[NSString class]]) {
        condition.cur_level = @([curLevelValue integerValue]);
    } else if ([curLevelValue isKindOfClass:[NSNumber class]]) {
        condition.cur_level = curLevelValue;
    }
    
    // 处理level_interval，可能是字符串或数字
    id levelIntervalValue = dictionary[@"level_interval"];
    if ([levelIntervalValue isKindOfClass:[NSString class]]) {
        condition.level_interval = @([levelIntervalValue integerValue]);
    } else if ([levelIntervalValue isKindOfClass:[NSNumber class]]) {
        condition.level_interval = levelIntervalValue;
    }
    
    // 处理ad_mob_first，可能是字符串或数字或布尔值
    id adMobFirstValue = dictionary[@"ad_mob_first"];
    if ([adMobFirstValue isKindOfClass:[NSString class]]) {
        condition.ad_mob_first = @([adMobFirstValue boolValue]);
    } else if ([adMobFirstValue isKindOfClass:[NSNumber class]]) {
        condition.ad_mob_first = adMobFirstValue;
    }
    
    // 处理其他扩展条件，包括ad_daily_limit和ad_wait_time等
    NSMutableDictionary *additionalConditions = [NSMutableDictionary dictionary];
    NSArray *knownKeys = @[@"cur_level", @"level_interval", @"ad_mob_first"];
    
    for (NSString *key in dictionary.allKeys) {
        if (![knownKeys containsObject:key]) {
            id value = dictionary[key];
            // 对于数字类型的字段，确保正确转换
            if ([key isEqualToString:@"ad_daily_limit"] || [key isEqualToString:@"ad_wait_time"]) {
                if ([value isKindOfClass:[NSString class]]) {
                    additionalConditions[key] = @([value integerValue]);
                } else if ([value isKindOfClass:[NSNumber class]]) {
                    additionalConditions[key] = value;
                } else {
                    additionalConditions[key] = @(0); // 默认值
                }
            } else {
                additionalConditions[key] = value;
            }
        }
    }
    
    if (additionalConditions.count > 0) {
        condition.additionalConditions = [additionalConditions copy];
    }
    
    return condition;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMAdCondition: cur_level=%@, level_interval=%@, ad_mob_first=%@, additional=%@>", 
            self.cur_level, self.level_interval, self.ad_mob_first, self.additionalConditions];
}

@end

@implementation IMAdStrategy

+ (instancetype)strategyFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[AdStrategy] 策略字典为空或类型错误");
        return nil;
    }
    
    IMAdStrategy *strategy = [[IMAdStrategy alloc] init];
    // 处理rate，可能是字符串或数字
    id rateValue = dictionary[@"rate"];
    if ([rateValue isKindOfClass:[NSString class]]) {
        strategy.rate = [rateValue integerValue];
    } else if ([rateValue isKindOfClass:[NSNumber class]]) {
        strategy.rate = [rateValue integerValue];
    } else {
        strategy.rate = 0; // 默认值
        NSLog(@"[AdStrategy] rate类型异常: %@", rateValue);
    }
    strategy.strategy_id = dictionary[@"strategy_id"];
    // 处理ad_status，可能是字符串或数字
    id adStatusValue = dictionary[@"ad_status"];
    if ([adStatusValue isKindOfClass:[NSString class]]) {
        strategy.ad_status = [adStatusValue integerValue];
    } else if ([adStatusValue isKindOfClass:[NSNumber class]]) {
        strategy.ad_status = [adStatusValue integerValue];
    } else {
        strategy.ad_status = 0; // 默认值
        NSLog(@"[AdStrategy] ad_status类型异常: %@", adStatusValue);
    }
    
    // 解析广告条件
    NSDictionary *adCondDict = dictionary[@"ad_cond"];
    if (adCondDict && [adCondDict isKindOfClass:[NSDictionary class]]) {
        strategy.ad_cond = [IMAdCondition conditionFromDictionary:adCondDict];
        if (!strategy.ad_cond) {
            NSLog(@"[AdStrategy] ad_cond解析失败: %@", adCondDict);
        }
    } else if (adCondDict) {
        NSLog(@"[AdStrategy] ad_cond字段不是字典类型: %@", adCondDict);
    }
    
    return strategy;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMAdStrategy: rate=%ld, strategy_id=%@, ad_status=%ld, ad_cond=%@>", 
            (long)self.rate, self.strategy_id, (long)self.ad_status, self.ad_cond];
}

@end

@implementation IMAdSceneStrategy

+ (instancetype)sceneStrategyFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[AdStrategy] 场景策略字典为空或类型错误");
        return nil;
    }
    
    IMAdSceneStrategy *sceneStrategy = [[IMAdSceneStrategy alloc] init];
    sceneStrategy.scene_name = dictionary[@"scene_name"];
    sceneStrategy.scene_desc = dictionary[@"scene_desc"];
    sceneStrategy.country = dictionary[@"country"];
    // 处理user_type，可能是字符串或数字
    id userTypeValue = dictionary[@"user_type"];
    if ([userTypeValue isKindOfClass:[NSString class]]) {
        sceneStrategy.user_type = [userTypeValue integerValue];
    } else if ([userTypeValue isKindOfClass:[NSNumber class]]) {
        sceneStrategy.user_type = [userTypeValue integerValue];
    } else {
        sceneStrategy.user_type = 0; // 默认值
        NSLog(@"[AdStrategy] user_type类型异常: %@", userTypeValue);
    }
    
    // 解析策略数组
    NSArray *strategyArray = dictionary[@"strategy"];
    if (strategyArray && [strategyArray isKindOfClass:[NSArray class]]) {
        NSMutableArray *strategies = [NSMutableArray array];
        for (int i = 0; i < strategyArray.count; i++) {
            NSDictionary *strategyDict = strategyArray[i];
            if (![strategyDict isKindOfClass:[NSDictionary class]]) {
                NSLog(@"[AdStrategy] 策略数据[%d]不是字典类型: %@", i, strategyDict);
                continue;
            }
            
            IMAdStrategy *strategy = [IMAdStrategy strategyFromDictionary:strategyDict];
            if (strategy) {
                [strategies addObject:strategy];
            } else {
                NSLog(@"[AdStrategy] 策略[%d]解析失败: %@", i, strategyDict);
            }
        }
        sceneStrategy.strategy = [strategies copy];
    } else {
        NSLog(@"[AdStrategy] strategy字段不是数组类型: %@", strategyArray);
        sceneStrategy.strategy = @[]; // 设置默认值
    }
    
    return sceneStrategy;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMAdSceneStrategy: scene_name=%@, scene_desc=%@, country=%@, user_type=%ld, strategies=%lu>", 
            self.scene_name, self.scene_desc, self.country, (long)self.user_type, (unsigned long)self.strategy.count];
}

@end

@implementation IMAdStrategyResponse

+ (instancetype)responseFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) {
        NSLog(@"[AdStrategy] 响应字典为空或类型错误");
        return nil;
    }
    
    IMAdStrategyResponse *response = [[IMAdStrategyResponse alloc] init];
    // 处理code，可能是字符串或数字
    id codeValue = dictionary[@"code"];
    if ([codeValue isKindOfClass:[NSString class]]) {
        response.code = [codeValue integerValue];
    } else if ([codeValue isKindOfClass:[NSNumber class]]) {
        response.code = [codeValue integerValue];
    } else {
        response.code = 0; // 默认值
    }
    response.message = dictionary[@"message"] ?: @"";
    
    // 解析数据数组
    NSArray *dataArray = dictionary[@"data"];
    if (dataArray && [dataArray isKindOfClass:[NSArray class]]) {
        NSMutableArray *sceneStrategies = [NSMutableArray array];
        for (int i = 0; i < dataArray.count; i++) {
            NSDictionary *sceneDict = dataArray[i];
            if (![sceneDict isKindOfClass:[NSDictionary class]]) {
                NSLog(@"[AdStrategy] 场景数据[%d]不是字典类型: %@", i, sceneDict);
                continue;
            }
            
            IMAdSceneStrategy *sceneStrategy = [IMAdSceneStrategy sceneStrategyFromDictionary:sceneDict];
            if (sceneStrategy) {
                [sceneStrategies addObject:sceneStrategy];
            } else {
                NSLog(@"[AdStrategy] 场景策略[%d]解析失败: %@", i, sceneDict);
            }
        }
        response.data = [sceneStrategies copy];
    } else {
        NSLog(@"[AdStrategy] data字段不是数组类型: %@", dataArray);
        response.data = @[]; // 设置为空数组而不是nil
    }
    
    return response;
}

- (BOOL)isSuccess {
    return self.code == 200;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<IMAdStrategyResponse: code=%ld, message=%@, data_count=%lu>", 
            (long)self.code, self.message, (unsigned long)self.data.count];
}

@end